﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceModel;
using System.ServiceProcess;
using System.Text;
using MiniStock.BusinessLogic.EventDispatcher;
using MiniStock.Entities;
using MiniStock.Infrastructure;
using Microsoft.Practices.Unity;
using MiniStock.Infrastructure.Configurator;

namespace MiniStockEventDispatcherHost
{
    public partial class EventDispatcherService : ServiceBase
    {
        private List<EventDispatcherWorker> _workers = new List<EventDispatcherWorker>();
        private ServiceHost _commandHost;
        private ServiceHost _queryHost;

        public EventDispatcherService()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            using (new MiniStockContextScope())
            {
                var configurator = MiniStockContext.Current.RootContainer.Resolve<IEventDispatcherConfigurator>();

                for (int i = 0; i < configurator.GetThreadCount();i++ )
                {
                    _workers.Add(MiniStockContext.Current.RootContainer.Resolve<EventDispatcherWorker>());
                    _workers[i].Configure(i);
                }

                _workers.ForEach(i => i.SignalStart());
                _workers.ForEach(i => i.Start());
            }

            _commandHost = new ServiceHost(typeof(MiniStock.ServiceFacade.ServiceFacade), new Uri("http://localhost:999/command"));
            _queryHost = new ServiceHost(typeof(MiniStock.ServiceFacade.Stock.StockServiceFacade), new Uri("http://localhost:999/query"));
            _commandHost.Open();
            _queryHost.Open();
        }

        protected override void OnStop()
        {
            _commandHost.Close();
            _queryHost.Close();
            _workers.ForEach(i => i.SignalStop());
            _workers.ForEach(i => i.Stop());
        }
    }
}
